package org.example.servlet;

import org.example.DAO.BlogCommentDAO;
import org.example.entity.BlogComment;
import org.example.DAO.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/blog/detail")
public class BlogDetailsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try (Connection conn = DBUtil.getConnection()) {
            BlogCommentDAO commentDAO = new BlogCommentDAO(conn);

            String blogId = req.getParameter("blogId");
            if (blogId == null || blogId.trim().isEmpty()) {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().write("参数缺失：blogId");
                return;
            }

            List<BlogComment> comments = commentDAO.getCommentsByBlogId(blogId);
            req.setAttribute("comments", comments);
            req.getRequestDispatcher("/blog-detail.jsp").forward(req, resp);

        } catch (SQLException e) {
            e.printStackTrace();
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write("服务器错误：" + e.getMessage());
        }
    }
}